<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
          >
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            size="mini"
            plain
            icon="el-icon-edit"
            :disabled="buttonState.editDisabled"
          >
            修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            size="mini"
            plain
            icon="el-icon-delete"
            :disabled="buttonState.delDisabled"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </el-col>
        <right-toolbar @queryTable="getData"></right-toolbar>
      </el-row>
     </div>
     <el-table
       :data="data"
       style="width: 100%"
       @selection-change="handleSelectionChange"
       v-loading="loading">
       <el-table-column
        type="selection"
        width="60"
        align="center"
       ></el-table-column>
       <el-table-column
         prop="questionId"
         label="编号"
         width="80">
       </el-table-column>
       <el-table-column
         prop="question"
         label="安全问题"
         width="450"
         show-overflow-tooltip>
       </el-table-column>
       <el-table-column
        label="创建时间"
        prop="createdTime"
        width="200"
        align="center"
      />
      <el-table-column
        label="修改时间"
        prop="updatedTime"
        width="200"
        align="center"
      />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row.questionId)"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row.questionId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
     </el-table>
     <Pagination
      v-show="totalCount > 0"
      :total="totalCount"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.limit"
      @pagination="getData"
    />

    <el-dialog
      :title="title"
      :visible.sync="open"
      width="400px">
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item label="安全问题" prop="question">
          <el-input v-model="form.question" placeholder="请输入安全问题" minlength="1" maxlength="50" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" :disabled="buttonState.submitDisabled" @click.native="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Security",
  data () {
    return {
      data: null,
      queryParams: {
        page: 1,
        limit: 10
      },
      totalCount: 0,
      buttonState: {
        editDisabled: true,
        delDisabled: true,
        submitDisabled: false
      },
      form: {},
      rules: {
        question:[
          { required: true, message: "安全问题不能为空", trigger: 'blur' },
          { min: 1, max: 50, message: "长度在 1~50 个字符", trigger: "blur"}
        ]
      },
      open: false,
      title: undefined,
      ids: [],
      loading: false
    };
  },
  created() {
    this.getData();
  },
  methods: {
    handleDelete(id) {
      this.$confirm('此操作将永久删除安全问题是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let qId = id || this.ids;
        this.deleteRequest(`/manage/security/${qId}`).then(() => {
          // 判断删除之后页码数是否发生变化
          let totalPage = 0; 
          if (id instanceof Array) {
            // 批量删除
            totalPage = Math.ceil((this.totalCount - id.length) / this.queryParams.limit); // 剩余数据总页数
            this.totalCount -= id.length;
          } else {
            // 单条删除
            totalPage = Math.ceil((this.totalCount - 1) / this.queryParams.limit); // 剩余数据总页数
            this.totalCount -= 1;
          }

          this.queryParams.page = this.queryParams.page > totalPage ? totalPage : this.queryParams.page
          this.queryParams.page = this.queryParams.page < 1 ? 1 : this.queryParams.page

          this.getData()
        })
      }).catch(() => {});
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.buttonState.submitDisabled = true;
          if (!this.form.questionId) {
            // 新增
            this.postRequest('/manage/security/', this.form).then(resp => {
              this.buttonState.submitDisabled = false;
              this.open = false;
              // 新增成功，跳转到最后一页
              this.totalCount += 1;
              let totalPage = Math.ceil(this.totalCount / this.queryParams.limit);
              this.queryParams.page = this.queryParams.page > totalPage ? this.queryParams.page : totalPage
              this.getData();
            }).catch(() => {
              this.buttonState.submitDisabled = false;
            });
          } else {
            // 修改
            this.putRequest('/manage/security/', this.form).then(resp => {
              this.buttonState.submitDisabled = false;
              this.open = false;
              this.getData();
            }).catch(() => {
              this.buttonState.submitDisabled = false;
            });
          }
        }
      });
    },
    handleSelectionChange(val) {
      this.ids = val.map(item => item.questionId);

      if (this.ids.length <= 0) {
        this.buttonState.delDisabled = true
      } else {
        this.buttonState.delDisabled = false
      }

      if (this.ids.length == 1) {
        this.buttonState.editDisabled = false
      } else {
        this.buttonState.editDisabled = true
      }
    },
    handleUpdate(id) {
      let questionId = id || this.ids[0];
      this.getRequest(`/manage/security/${questionId}`).then(resp => {
        if (resp) {
          this.reset();
          this.form = resp.data;
          this.open = true;
          this.title = "修改密保模板";
        }
      })
    },
    cancel() {
      this.open = false;
      setTimeout(() => {
        this.reset();
      }, 200);
    },
    handleAdd() {
      this.reset();
      this.title = "新增安全问题";
      this.open = true;
    },
    reset() {
      this.form = {
        questionId: undefined,
        question: undefined
      };
      this.resetForm('form');
    },
    getData() {
      this.loading = true;
      this.getRequest('/manage/security/', this.queryParams).then(resp => {
        if (resp) {
          this.data = resp.data.list;
          this.totalCount = Number(resp.data.total);
          this.loading = false;
        }
      });
    }
  }
}

</script>
<style lang='scss' scoped>
  .app-container {
    .filter-container {
      padding-top: 0;
    }
  }
</style>